from collections import namedtuple


# 具名函数
def greeting(name):
    print("name=", name)


print("id(greeting)=", id(greeting))


# 匿名函数,  不用写def 关键字来定义，类似于JS的匿名函数
square = lambda x: x**2

print(f"square = {id(square)}", square(10))


# 在排序中使用匿名函数

students = [
    {"name": "Alice", "grade": 85},
    {"name": "Bob", "grade": 92},
    {"name": "Charlie", "grade": 78},
]
sorted_students = sorted(students, key=lambda x: x["grade"])
print("sorted_students=", sorted_students)


# 定义一个具名元组
Persons = namedtuple("PersonTupe", "name age chinese math")

person_list = [
    Persons("alice", 28, 100, 90),
    Persons("linda", 30, 87, 87),
    Persons("susan", 25, 56, 24),
    Persons("bob", 18, 78, 12),
]

sorted_person_list = sorted(person_list, key=lambda x: x.age)
sorted_chinese_person_list = sorted(person_list, key=lambda x: x.chinese)
sorted_math_person_list = sorted(person_list, key=lambda x: x.math)


def print_person_info(list_obj):
    print(f"{'姓名':<10}\t{'年龄':<10}\t{'语文':<10}\t{'数学':<10}")
    for name, age, chinese, math in list_obj:
        print(f"{name:<10}\t{age:<10}\t{chinese:<10}\t{math:<10}\n")


print("=" * 60)
print_person_info(person_list)

print("=" * 60)
print_person_info(sorted_person_list)

print("=" * 60)
print_person_info(sorted_chinese_person_list)

print("=" * 60)
print_person_info(sorted_math_person_list)

# 匿名函数在map 和 filter函数中的使用
nums_list = [1, 2, 3, 4, 5, 6]

double_nums_list = list(map(lambda x: x * 2, nums_list))
print("double_nums_list=", double_nums_list)

filter_nums_list = list(filter(lambda x: x % 2 == 0, nums_list))
print("filter_nums_list=", filter_nums_list)
